Passed
Pull Request — master (#136)
by
unknown
01:48
created

FrameBuilder.getBuffer   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
1
import * as ID3Util from "./ID3Util"
2
import { isString } from "./util"
3
import { TextEncoding } from "./definitions/Encoding"
4
5
type Value = Buffer | number | string
6
7
export class FrameBuilder {
8
    private identifier: string
9
    private buffer = Buffer.alloc(0)
10
11
    constructor(identifier: string) {
12
        this.identifier = identifier
13
    }
14
15
    appendValue(
16
        value: Value,
17
        size: number,
18
        encoding = TextEncoding.ISO_8859_1
19
    ) {
20
        const convertedValue = convertValue(value, encoding)
21
        this.appendBuffer(staticValueToBuffer(convertedValue, size))
22
        return this
23
    }
24
25
    appendNumber(value: number, size: number) {
26
        if (Number.isInteger(value)) {
27
            let hexValue = value.toString(16)
28
            if (hexValue.length % 2 !== 0) {
29
                hexValue = "0" + hexValue
30
            }
31
            this.appendBuffer(
32
                staticValueToBuffer(Buffer.from(hexValue, 'hex'), size)
33
            )
34
        }
35
        return this
36
    }
37
38
    appendNullTerminatedValue(value = '', encoding = TextEncoding.ISO_8859_1) {
39
        this.appendBuffer(
40
            convertValue(value, encoding),
41
            getTerminatingMarker(encoding)
42
        )
43
        return this
44
    }
45
46
    getBuffer() {
47
        const header = Buffer.alloc(10)
48
        header.write(this.identifier, 0)
49
        header.writeUInt32BE(this.buffer.length, 4)
50
        return Buffer.concat([header, this.buffer])
51
    }
52
53
    private appendBuffer(...buffers: Buffer[]) {
54
        this.buffer = Buffer.concat([this.buffer, ...buffers])
55
    }
56
}
57
58
function convertValue(value: Value, encoding = TextEncoding.ISO_8859_1) {
59
    if (value instanceof Buffer) {
60
        return value
61
    }
62
    if (Number.isInteger(value) || isString(value)) {
63
        return ID3Util.stringToEncodedBuffer(value.toString(), encoding)
64
    }
65
    return Buffer.alloc(0)
66
}
67
68
function staticValueToBuffer(buffer: Buffer, size: number) {
69
    if (size && buffer.length < size) {
70
        return Buffer.concat([Buffer.alloc(size - buffer.length, 0x00), buffer])
71
    }
72
    return buffer
73
}
74
75
function getTerminatingMarker(encoding: number) {
76
    if (encoding === TextEncoding.UTF_16_WITH_BOM ||
77
        encoding === TextEncoding.UTF_16_BE
78
    ) {
79
        return Buffer.alloc(2, 0x00)
80
    }
81
    return Buffer.alloc(1, 0x00)
82
}
83
84